package nickthissen.iracing.activities;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Spinner;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.internal.widget.IcsSpinner;

import org.apache.http.impl.client.BasicCookieStore;

import java.net.CookieStore;
import java.util.ArrayList;

import nickthissen.iracing.adapters.PagerAdapter;
import nickthissen.iracing.common.Prefs;
import nickthissen.iracing.common.PrivateStore;
import nickthissen.iracing.common.Redirect;
import nickthissen.iracing.datamodels.Page;
import nickthissen.iracing.datamodels.User;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.NetworkMethod;

/**
 * Created by nthissen on 20/09/13.
 */
public class LoadingActivity extends SherlockActivity
{
    private Redirect redirect;
    private final static int REQ_TRYLOAD = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spinnertest);

        // Handle redirects (from other apps)
        Uri data = this.getIntent().getData();
        redirect = Redirect.handleData(data);

        if (Prefs.get(this).getBoolean(R.string.PREF_LoginCaching, true))
        {
            // Get stored user
            User user = PrivateStore.getStoredLogin(this);
            if (user != null)
            {
                User.currentUser = user;

                // Load cookies (null if not found or wrong user)
                BasicCookieStore store = PrivateStore.getStoredCookies(this, user.username);
                NetworkMethod.setCookieStore(store);

                if (store == null)
                {
                    this.sendToLogin();
                }
                else
                {
                    this.tryLoad();
                }
            }
            else
            {
                this.sendToLogin();
            }
        }
        else
        {
            this.sendToLogin();
        }
    }

    private void tryLoad()
    {
        Intent intent = MainActivity.getIntent(this, redirect, true);
        this.startActivityForResult(intent, REQ_TRYLOAD);
    }

    private void sendToLogin()
    {
        User.currentUser = null;
        Intent intent = LoginActivity.getIntent(this, redirect);
        this.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQ_TRYLOAD)
        {
            if (resultCode == RESULT_CANCELED)
            {
                // Loading failed, try login
                this.sendToLogin();
            }
            finish();
        }
        else
        {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
